import { NextApiResponse } from '@/libs/apiResponse';
import { ChatClient } from 'dify-client';
import { type NextRequest } from 'next/server';
import { z } from 'zod';

const AnalyseFlowImageSchema = z.object({
  url: z.string(),
});

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    const validatedData = AnalyseFlowImageSchema.parse(body);

    const baseUrl = process.env.DIFY_API_URL;
    const client = new ChatClient('app-ILBGA5MnLckj4DSITsesX476', baseUrl);

    const response = await client.createChatMessage(
      {},
      '分析图片',
      'ruanzhu',
      false,
      '',
      [
        {
          type: 'image',
          transfer_method: 'remote_url',
          url: validatedData.url,
        } as unknown as File,
      ]
    );

    const text = response.data.answer;

    return NextApiResponse.success(
      {
        text,
      },
      'AI 分析完成'
    );
  } catch (error) {
    console.error(error);

    if (error instanceof z.ZodError) {
      return NextApiResponse.badRequest('请求参数验证失败');
    }

    return NextApiResponse.serverError('服务器内部错误');
  }
}
